package com.tcm.core.service;

import com.base.core.dozer.DozerConvert;
import com.base.core.exception.ServiceException;
import com.base.core.tree.TreeParser;
import com.tcm.core.domain.dto.AreasDTO;
import com.tcm.core.domain.entity.Areas;
import com.tcm.core.mapper.AreasMapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@DubboService(version = "0.0.1-alpha", retries = 3, delay = -1)
public class AreasServiceImpl implements AreasService{

    @Autowired
    private AreasMapper areasMapper;

    private final TreeParser<AreasDTO> parser = new TreeParser<>();

    /**
     * 获取一级子分类
     * @param parentId
     * @return
     * @throws Exception
     */
    @Override
    public List<AreasDTO> listSubAreas(Long parentId) throws Exception {
        return listSubAreas(parentId,false);
    }

    /**
     * 查询分类数据
     * @param id
     * @return
     */
    @Override
    public AreasDTO findById(Long id) {
        Areas areas = areasMapper.findById(id);
        return DozerConvert.copyProperties(areas,AreasDTO.class);
    }

    /**
     * 获取所有地区
     * @return
     * @throws Exception
     */
    @Override
    public List<AreasDTO> listAreas() throws ServiceException {
        List<Areas> areasList = areasMapper.listAreas();
        return DozerConvert.copyList(areasList, AreasDTO.class);
    }

    /**
     * 转换为树形结构
     *
     * @return
     * @throws Exception
     */
    @Override
    public List<AreasDTO> listToTree() {

        List<Areas> areasList = areasMapper.listAreas();
        List<AreasDTO> selectAreasDTOs = DozerConvert.copyList(areasList, AreasDTO.class);
        TreeParser<AreasDTO> selectParser = new TreeParser<>();
        return selectParser.treeList(1L,selectAreasDTOs);
    }

    /**
     * 递归查询子类
     * @param parentId 父类id
     * @param recursive
     * @return
     * @throws Exception
     */
    @Override
    public List<AreasDTO> listSubAreas(Long parentId, boolean recursive) throws Exception {
        if(!recursive){
            List<Areas> areasList = areasMapper.listChild(parentId);
            System.out.println(DozerConvert.copyList(areasList,AreasDTO.class));
            return DozerConvert.copyList(areasList,AreasDTO.class);
        }
        List<AreasDTO> AreasDTOList = DozerConvert.copyList(listAreas(),AreasDTO.class);
        return parser.findChildNodes(AreasDTOList, parentId);
    }

}
